<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\logic;

use app\library\redis\Redis;

class Group
{
    const PREFIX = 'group_';

    const MSG = 'group_msg';

    const OPERA_ADD = 'add';

    const OPERA_RM = 'remove';

    /**
     * 获取群组信息
     * @param string $groupId
     * @param array $exclude
     * @return array
     */
    static function getUserIdList(string $groupId, array $exclude = [])
    {
        $redis = Redis::get();
        $members = $redis->sMembers(self::PREFIX . $groupId);
        $members = array_diff($members, $exclude);
        Redis::put($redis);
        return $members;
    }


    /**
     * 获取群成员信息
     * @param string $groupId
     * @param array $exclude
     */
    static function getUserList(string $groupId, array $exclude = [])
    {
        $userIdMap = self::getUserIdList($groupId, $exclude);
        $userInfo = [];
        foreach ($userIdMap as $userId) {
            $userInfo[] = Users::getUserById($userId);
        }
        return $userInfo;
    }

    /**
     * 添加把某人加入群聊
     * @param string $userId
     * @param string $groupId
     * @return bool|int
     */
    static function add(string $userId, string $groupId)
    {
        $redis = Redis::get();
        $members = $redis->sAdd(self::PREFIX . $groupId, $userId);
        Redis::put($redis);
        return $members;
    }

    /**
     * 把某人踢出群聊
     * @param array $userId
     * @param string $groupId
     */
    static function remove(string $userId, string $groupId)
    {
        $redis = Redis::get();
        $members = $redis->sRem(self::PREFIX . $groupId, $userId);
        Redis::put($redis);
        return $members;
    }

    /**
     * 批量操作
     * @param string $event
     * @param string $groupId
     * @param array $userIdMap
     * @return bool
     */
    static function batch(string $event = self::OPERA_ADD, string $groupId, array $userIdMap)
    {
        $success = 0;
        foreach ($userIdMap as $userId) {
            if (self::$event($userId, $groupId)) {
                ++$success;
            }
        }
        return $success == count($userIdMap);
    }

    static function getMsgIdList(string $groupId)
    {
        $redis = Redis::get();
        $members = $redis->sMembers(self::MSG . $groupId);
        Redis::put($redis);
        return $members;
    }

    static function getMsgList(string $groupId)
    {
        $msgIdList = self::getMsgIdList($groupId);
        $messages = [];
        foreach ($msgIdList as $msgId) {
            $messages[] = Messages::get($msgId);
        }
        return $messages;
    }
}
